package cn.z2huo.usercenter.authentication.app.config;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * <p>
 *
 * @author z2huo
 */
@EnableAsync
@Configuration
@ComponentScan(basePackages = "cn.z2huo.usercenter.authentication.app")
public class AsyncConfig implements AsyncConfigurer {

//    @Bean(value = "CustomThreadPoolExecutor", destroyMethod = "shutdown")
//    @Primary
    @Override
    public ThreadPoolTaskExecutor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数数量
        // cpu 逻辑处理器数量
        executor.setCorePoolSize(Runtime.getRuntime().availableProcessors());
        // 最大线程数量
        // cpu 逻辑处理器数量的 2 倍
        executor.setMaxPoolSize(Runtime.getRuntime().availableProcessors() * 2);
        // 最大队列容量
        executor.setQueueCapacity(64);
        executor.setThreadNamePrefix("custom-task-executor-");
        // 线程池对拒绝任务的处理策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 控制线程池中超过核心线程数的线程在空闲状态下的存活时间
        executor.setKeepAliveSeconds(60);

        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);
        executor.setAllowCoreThreadTimeOut(false);
        executor.initialize();

        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return AsyncConfigurer.super.getAsyncUncaughtExceptionHandler();
    }
}
